<?php
/**
 * Created by PhpStorm.
 * User: jimmyhsu
 * Date: 2016/10/24
 * Time: 13:53
 */
//连接到数据库并检查用户是否合法，checkvalid.php是服务器上我写好的一个文件,你本地没有，报错是正常的
include ("checkvalid.php");
$userid = $checkRow['id'];
$name = $_POST['username'];
$title = $_POST['title'];
$content = $_POST['content'];
$price = $_POST['price'];
$type = $_POST['type'];
$lat = $_POST['lat'];
$longt = $_POST['longt'];
$contact = $_POST['contact'];
$imageCount = $_POST['imagecount'];
$time = time() * 1000;
$sql = "insert into dwtb (id, userid, title, content, price, type, lat, longt, time, validtru, status, username, imageurls, contact) values (
NULL, $userid, '$title', '$content', $price, $type, $lat, $longt, $time, -1, 1, '$name', '', '$contact')";
mysql_query($sql);
$insertId = mysql_insert_id();

if ($imageCount > 0) {

    $insertId = mysql_insert_id();
    $uploads_dir = "C:\\PHPWAMP\\wwwroot\\phpprojects\\dwimage";
    $imageUrls = "";
    for ($i = 1; $i <= $imageCount; $i++) {
        if ((($_FILES["file".$i]["type"] == "image/jpeg")
            || ($_FILES["file".$i]["type"] == "image/jpg")
            || ($_FILES["file".$i]["type"] == "image/png"
            )))
        {
            if ($_FILES["file".$i]["error"] > 0)
            {
				mysql_query("delete from dwtb where id=$insertId");
                die("Return Code: " . $_FILES["file"]["error"] . "<br />");
            }
            else
            {
                $name = basename($_FILES["file".$i]["name"]);
                $extension = pathinfo("$uploads_dir/$name", PATHINFO_EXTENSION);
                move_uploaded_file($_FILES["file".$i]["tmp_name"],
                    $uploads_dir."\\".$insertId."-".$i.'.'.$extension);
                if ($i > 1) {
                    $imageUrls = $imageUrls.";";
                }
                $imageUrls = $imageUrls."dwimage/".$insertId."-".$i.'.'.$extension;
            }
        }
        else
        {
			mysql_query("delete from dwtb where id=$insertId");
            die("Invalid file".$_FILES["file".$i]["type"]);
        }
    }
    $sql = "update dwtb set imageurls='$imageUrls' where id=$insertId";
    if (!mysql_query($sql)) {
		mysql_query("delete from dwtb where id=$insertId");
		die("fail");
	}
} else {
	$sql = "update dwtb set imageurls='no_image' where id=$insertId";
    if (!mysql_query($sql)) {
		mysql_query("delete from dwtb where id=$insertId");
		die("fail");
	}
}
//foreach ($_FILES["imgFile"]["error"] as $key=>$error) {
//    if ($error == UPLOAD_ERR_OK) {
//        $tmp_name = $_FILES["pictures"]["tmp_name"][$key];
//        // basename() may prevent filesystem traversal attacks;
//        // further validation/sanitation of the filename may be appropriate
//        $name = basename($_FILES["pictures"]["name"][$key]);
//        $extension = pathinfo("$uploads_dir/$name", PATHINFO_EXTENSION);
//        move_uploaded_file($tmp_name, "$uploads_dir/$insertId"."-".$i.".".$extension);
//        $i++;
//    }
//}
    echo "success";
